package product

import (
	"context"
	"group-buy/group_buy/internal/models"

	"group-buy/group_buy/internal/svc"
	"group-buy/group_buy/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type EnumProductLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewEnumProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EnumProductLogic {
	return &EnumProductLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *EnumProductLogic) EnumProduct(req *types.EnumProductReq) (resp *types.EnumProductRsp, err error) {
	data := make([]*models.Product, 0)
	sql := l.svcCtx.Engine.Where("")
	if req.BusinessId > 0 {
		sql = sql.And("business_id=?", req.BusinessId)
	}

	err = sql.OrderBy("sort").Find(&data)
	if err != nil {
		return nil, err
	}
	list := make([]*types.EnumProduct, len(data), len(data))
	for i, _ := range data {
		businessName:=""
		business:=&models.Business{Id: data[i].BusinessId}

		get, err := l.svcCtx.Engine.Get(business)
		if err != nil {
			return nil, err
		}
		if get {
			businessName=business.Name
		}

		list[i] = &types.EnumProduct{
			Id:   data[i].Id,
			Name: data[i].Name,
			BusinessName: businessName,
		}
	}

	return &types.EnumProductRsp{
		List: list,
	}, nil
}
